<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/22 0022
 * Time: 上午 8:46
 */

header('content-type:text/html;charset=utf-8');

$error=array();
if (!empty($_POST)){
    $username=isset($_POST['username'])?trim($_POST['username']):'';
    $password=isset($_POST['password'])?$_POST['password']:'';
    //载入表单验证函数库，验证用户名密码和格式
    require 'check_form.lib.php';
    if (($result=checkUsername($username))!==true) $error[]=$result;
    if (($result=checkPassword($password))!==true) $error[]=$result;

    //表单验证通过，再到数据库中验证
    if (empty($error)){
        $link=mysqli_connect('localhost','root','123456');
        if (!$link){
            die('连接数据库失败！'.mysqli_error($link));
        }
        mysqli_query($link,'set names utf8');
        mysqli_query($link,'use `itcast`');

        //处理用户名和密码
        $username=mysqli_real_escape_string($link,$username);//SQL转义
        //根据用户名提取出用户信息
        $sql="select `id`,`password` from `user` where `username`='$username'";
        if ($rst=mysqli_query($link,$sql)){
            $row=mysqli_fetch_assoc($rst);
            $password=md5($password);
            if ($password==$row['password']){
                die('欢迎登录！');
            }
        }
        $error[]='用户名不存在或密码错误。';
    }
}
